package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.SysUserbean;
import com.ruoyi.system.domain.User;
import com.ruoyi.system.domain.ZftAppMyManager;
import com.ruoyi.system.domain.dto.RegisterDTO;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.mapper.ZftAppMyManagerMapper;
import com.ruoyi.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ZftAppMyManagerMapper zftAppMyManagerMapper;
    //根据用户名查询用户

    //学号初始值
    private static int lastId = 999; // 初始值设为999，这样第一个生成的ID是1000

    /**
     * 用户注册
     *
     * @param registerDTO
     * @return
     */
    @Override
    @Transactional
    public void register(RegisterDTO registerDTO) {
        //获取用户名
        String username = registerDTO.getUserName();
        //获取密码
        String password = registerDTO.getPassword();
        //从缓存中取出验证码
        String KeyCode = (String) redisTemplate.opsForValue().get("keyCode");
        System.out.printf("缓存中取出的验证码：" + KeyCode);

        if (!KeyCode.equals(registerDTO.getKeyCode())) {
            throw new ServiceException("您输入的验证码不正确", 40001);
        }
        if (KeyCode == null) {
            throw new ServiceException("验证码已经过期", 40002);
        }

        //根据用户名查询用户
        SysUser sysUser = userMapper.selectUserByUserName(registerDTO.getUserName());
        if (sysUser != null) {
            throw new ServiceException("该账号已存在", 40003);
        }
        //根据用户手机号查询用户
        SysUser sysUser1 = userMapper.selectUserByPhoneNum(registerDTO.getPhoneNumber());
        if (sysUser1 != null) {
            throw new ServiceException("该手机号已经存在", 40004);
        }


        //将用户信息插入数据库
        SysUser user = new SysUser();
        //生成学号
        Integer studentNo = generateStudentId();
        user.setUserType("01");
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setUserName(username);
        user.setNickName(registerDTO.getNickName());
        user.setPhonenumber(registerDTO.getPhoneNumber());
        user.setRemark("app用户注册");
        user.setStudentNo(studentNo.toString());
//        //生成学号
//        String studentNo=generateStudentId();
//        SysUserbean user=new SysUserbean();
//        user.setUserType("01");
//        user.setPassword(SecurityUtils.encryptPassword(password));
//        user.setUserName(username);
//        user.setNickName(registerDTO.getNickName());
//        user.setRemark("app用户注册");
//        user.setStudentNo(studentNo);
        //删除缓存验证码
        redisTemplate.delete("KeyCode");

        userMapper.insertUser(user);
        ZftAppMyManager zftAppMyManager = new ZftAppMyManager();
        //关联上我的管理记录
        zftAppMyManager.setUserId(user.getUserId().toString());
        zftAppMyManager.setMyUuid(IdUtils.simpleUUID());
        //加入学号
        zftAppMyManager.setStudentNo(studentNo.toString());
        zftAppMyManagerMapper.insertZftMyManager(zftAppMyManager);
    }

    //生成学号
    public static  int generateStudentId() {
        int nextId;
        do {
            nextId = ++lastId;
            nextId++;
            // 确保至少从1000开始
            if (nextId < 1000) {
                nextId = lastId = 1000;
            }
        } while (containsFour(nextId));

        return nextId;
    }

    /**
     * 检查数字是否包含4
     * @param num 要检查的数字
     * @return 如果包含4返回true，否则返回false
     */
    private static boolean containsFour(int num) {
        while (num > 0) {
            int digit = num % 10;
            if (digit == 4) {
                return true;
            }
            num /= 10;
        }
        return false;
    }

}
